#include "rs485_1_tx_thread.h"


RS485_1_Tx_Thread::RS485_1_Tx_Thread(Serial_Port* sp)
{
    stop_flag = true;
    //(void)sp;
    this->serial_port = sp;

    connect(this,SIGNAL(signal_start_tx_thread()),this,SLOT(slot_rs485_1_port_tx_thread()));
    connect(this,SIGNAL(signal_start_rs485_1_port(char*,int)),this->serial_port,SLOT(slot_write_serial_port(char*,int)));
    connect(this->serial_port,SIGNAL(signal_byteswritten(qint64)),this,SLOT(slot_tx_semaphore_release(qint64)));

    //rs485_1_tx_sem.release();
}

RS485_1_Tx_Thread::~RS485_1_Tx_Thread()
{

}

void RS485_1_Tx_Thread::slot_tx_semaphore_release(qint64 bytes)
{
    (void )bytes;

    //qDebug() << "slot_tx_semaphore_release" << bytes;

    //rs485_1_tx_sem.release();
}

void RS485_1_Tx_Thread::slot_write_rs485_1_port_tx_queue(char *s, unsigned int len)
{
    if((len > 0) && (s != nullptr))
    {
        //serial_port->serial_port_tx_queue->circlebuff_write_packet_data(s,len);
        //emit signal_start_tx_thread();
        emit signal_start_rs485_1_port(s,(int)len);    //调用串口底层硬件进行数据发送
    }
}

void RS485_1_Tx_Thread::slot_rs485_1_port_tx_thread()
{    
    {
        QMutexLocker locker(&stop_mutex);
        stop_flag = false;
    }

    unsigned int data_len = 0;
    char data_buff[1024];

    while(1)
    {
        {
            QMutexLocker locker(&stop_mutex);
            if(stop_flag)return;
        }

        //tx_sem.acquire();
        //qDebug() << "slot_serial_port_tx_thread";
        //memset(data_buff,0x00,sizeof(data_buff));

        data_len = serial_port->serial_port_tx_queue->circlebuff_read_packet_data(data_buff);

        if(data_len > 0)
        {
            emit signal_start_rs485_1_port(data_buff,(int)data_len);    //调用串口底层硬件进行数据发送
        }
        else {
            stop_thread();
            //tx_sem.release();
        }
    }
}

void RS485_1_Tx_Thread::stop_thread()
{
    {
        QMutexLocker locker(&stop_mutex);
        stop_flag = true;
    }
}


